// pages/detail/detail.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: 0,
    gameIngInfo: {
      leader: 0,
      gameName: "",
      gameId:0,
      play: [],
      userList: [],
      resultInfo: []
    },
    showModalStatus: false,
    showNextStatus: false,
    showRecordStatus: false,
    recordData: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    this.getGameUser(e.game_id);
    this.setData({
      userId: e.user_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  handleRadio(e) {
    var that = this;
    var choiseId = e.currentTarget.dataset.userid;
    var winTypeValue = e.detail.value;
    var choiseId = winTypeValue.substring(0, winTypeValue.indexOf("#"))
    var winType = winTypeValue.substring(winTypeValue.lastIndexOf("#") + 1, winTypeValue.length)
    var itemsArray = that.data.gameIngInfo.resultInfo;
    itemsArray.forEach(function (item, index) {
      if (choiseId == item.userId ? true : false) {
        item.winType = Number(winType)
      }
    });
  },
  handleInput(e) {
    var that = this;
    var choiseId = e.currentTarget.dataset.userid;
    var inputMoney = e.detail.value;
    var itemsArray = that.data.gameIngInfo.resultInfo;
    itemsArray.forEach(function (item, index) {
      if (choiseId == item.userId ? true : false) {
        item.winMoney = Number(inputMoney)
      }
    });
  },
  deleteGame(e) {
    var that = this;
    var gameId = e.target.dataset.id;
    wx.request({
      url: app.globalData.serverIp + 'games/deleteGame',
      method: 'POST',
      data: {
        "gameId": gameId,
        "userId": 0
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.code != 0) {
          wx.showToast({
            icon: 'none',
            title: res.data.message
          });
        } else {
          that.setData({
            ["gameIngInfo.gameIngStatu"]: false
          });
          that.getGame()
        };
      }
    })
  },
  getGameUser(gameId) {
    var that = this;
    wx.cloud.callFunction({
      name: 'homePlayFuntions',
      config: {
        env: that.data.envId
      },
      data: {
        type: 'getUserPlayInfo',
        game: gameId
      }
    }).then((resp) => {
      var users = resp.result.game.data[0].users;
      var leader = resp.result.game.data[0].leaderId;
      var gameName = resp.result.game.data[0].gameName;
      var gameId = resp.result.game.data[0]._id;
      var play = resp.result.play.data;
      for (var i = 0; i < users.length; i++) {
        users[i].userIntegral = 0;
      };
      for (let user of users) {
        for (let p of play) {
          for (let r of p.result) {
            if (user.userId == r.userId) {
              if (r.winType == 2) {
                user.userIntegral -= r.winMoney;
              } else {
                user.userIntegral += r.winMoney;
              }
            }
          }
        };
      };
      var userResult = []
      for(let user of users){
        var userData = {"userId":user.userId,"winType":0,"winMoney":0};
        userResult.push(userData);
      }
      that.setData({
        ["gameIngInfo.userList"]: users,
        ["gameIngInfo.leader"]: leader,
        ["gameIngInfo.gameName"]: gameName,
        ["gameIngInfo.gameId"]: gameId,
        ["gameIngInfo.play"]: play,
        ["gameIngInfo.resultInfo"]: userResult,
      });
    }).catch((e) => {
      console.log(e);
    });
  },
  showRecord(e) {
    var that = this;
    var userId = e.target.dataset.userid;
    var gameId = e.target.dataset.gameid;
    var sta = e.target.dataset.statu;
    that.setData({
      showModalStatus: !that.data.showModalStatus,
      showRecordStatus: !that.data.showRecordStatus
    });
    if (sta == "close") {
      console.log("close")
    } else {
      wx.cloud.callFunction({
        name: 'homePlayFuntions',
        config: {
          env: that.data.envId
        },
        data: {
          type: 'getUserRecord',
          game: gameId
        }
      }).then((resp) => {
        var data_list = [];
        var count = 1;
        for (let res of resp.result.data){
          for(let userRes of res.result){
            if(userRes.userId == userId){
              var d = {"count": count, "winType": userRes.winType, "winMoney":userRes.winMoney};
              data_list.push(d);
            }
          };
          count += 1;
        };
        that.setData({
          recordData: data_list
        })
      }).catch((e) => {
        console.log(e);
      });
    }

  },
  addGamePlay(e) {
    var that = this;
    var gameId = e.currentTarget.dataset.gameid;
    var submitType = e.currentTarget.dataset.oprtype
    if (submitType == "submit") {
      var itemsArray = that.data.gameIngInfo.resultInfo;
      var totalWin = 0;
      var totalLost = 0;
      itemsArray.forEach(function (item, index) {
        if (item.winType == 1 || item.winType == 0) {
          totalWin += item.winMoney
        } else {
          totalLost += item.winMoney
        }
      });
      if (totalWin != 0 && (totalWin == totalLost)) {
        wx.cloud.callFunction({
          name: 'homePlayFuntions',
          config: {
            env: that.data.envId
          },
          data: {
            type: 'addGamePlay',
            game: gameId,
            result: itemsArray
          }
        }).then((resp) => {
          that.setData({
            showModalStatus: !that.data.showModalStatus,
            showNextStatus: !that.data.showNextStatus
          });
          that.getGameUser(gameId);
        }).catch((e) => {
          console.log(e);
        });
      } else {
        wx.showToast({
          icon: 'none',
          title: '输入不合理',
        })
      }
    } else {
      that.setData({
        showModalStatus: !that.data.showModalStatus,
        showNextStatus: !that.data.showNextStatus,
      })
    }

  }
})